<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="注意: 只允许为第三级分类设置相关参数"
                type="warning"
                show-icon>
      </el-alert>
      <el-row class="cat_opt">
        <el-col :span="2" class="cat_opt">
          <span>选择商品分类: </span>
        </el-col>
        <el-col :span="8">
          <el-cascader
            v-model="value"
            :options="allGoodsType"
            :props="{ expandTrigger: 'hover',
                    value: 'cat_id',
                    label: 'cat_name'}"
            show-all-levels
            @change="handleChange">
          </el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" class="tabs_top" @tab-click="tabClick">
        <!-- 表格1 -->
        <el-tab-pane label="动态参数" name="many" >
          <el-row :gutter="20">
            <el-col :span="4">
              <el-button type="primary" @click="addDialogVisible = true" :disabled="isBtnDisabled">添加参数</el-button>
            </el-col>
          </el-row>
          <el-table
            :data="manyParamsType"
            style="width: 100%;margin-bottom: 20px;"
            row-key="attr_id"
            border
            :tree-props="{children: 'children'}">
            <el-table-column type="expand">
              <template slot-scope="scoped">
                <el-tag closable
                        v-for="(item, i) in scoped.row.attr_vals"
                        :key="i"
                        @close="deleteTag(scoped.row, i)">{{ item }}
                </el-tag>
                <!-- 新增标签的input -->
                <el-input
                  class="input-new-tag"
                  v-if="scoped.row.inputVisible"
                  v-model="scoped.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scoped.row)"
                  @blur="handleInputConfirm(scoped.row)"
                >
                </el-input>
                <!-- 新增标签按钮 -->
                <el-button v-else class="button-new-tag"
                           size="small"
                           @click="showInput(scoped.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scoped">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="openUpdate(scoped.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRoles(scoped.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 表格2 -->
        <el-tab-pane label="静态属性" name="only">
          <el-row :gutter="20">
            <el-col :span="4">
              <el-button type="primary" @click="addDialogVisible = true" :disabled="isBtnDisabled">添加参数</el-button>
            </el-col>
          </el-row>
          <el-table
            :data="onlyParamsType"
            style="width: 100%;margin-bottom: 20px;"
            row-key="attr_id"
            border
            :tree-props="{children: 'children'}">
            <el-table-column type="expand">
              <template slot-scope="scoped">
                <el-tag closable
                        v-for="(item, i) in scoped.row.attr_vals"
                        :key="i"
                        @close="deleteTag(scoped.row, i)">{{ item }}
                </el-tag>
                <!-- 新增标签的input -->
                <el-input
                  class="input-new-tag"
                  v-if="scoped.row.inputVisible"
                  v-model="scoped.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scoped.row)"
                  @blur="handleInputConfirm(scoped.row)"
                >
                </el-input>
                <!-- 新增标签按钮 -->
                <el-button v-else class="button-new-tag"
                           size="small"
                           @click="showInput(scoped.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scoped">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="openUpdate(scoped.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRoles(scoped.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加属性弹窗 -->
    <el-dialog
      :title="title"
      :visible.sync="addDialogVisible"
      width="30%"
      @close="addDialogClose">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px" >
        <el-form-item label="属性" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAttr">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑属性弹窗 -->
    <el-dialog
      :title="editTitle"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="editDialogClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px" >
        <el-form-item label="属性" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="UpdateAttr">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  data () {
    return {
      allGoodsType: [],
      onlyParamsType: [],
      manyParamsType: [],
      addDialogVisible: false,
      editDialogVisible: false,
      value: '',
      activeName: 'many',
      addForm: {
        attr_name: '',
        attr_sel: [],
        attr_vals: ''
      },
      editForm: {
        attr_name: '',
        attr_sel: [],
        attr_vals: '',
        attr_id: 0
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 2, max: 10, message: '请输入2到10个字符', trigger: 'blur' }
        ]
      },
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
          { min: 2, max: 10, message: '请输入2到10个字符', trigger: 'blur' }
        ]
      },
      title: '添加动态参数',
      editTitle: '编辑动态参数'
    }
  },
  methods: {
    async getAllGoodsType () {
      const { data: res } = await this.$http.get('categories', { params: { type: [1, 2] } })
      if (res.meta.status !== 200) return this.$message.error('加载商品分类数据失败!')
      this.allGoodsType = res.data
    },
    async getParamsType () {
      // 获取value中的最后一个数字
      const { data: res } = await this.$http.get(`categories/${this.value[2]}/attributes`, { params: { sel: [this.activeName] } })
      if (res.meta.status !== 200) return this.$message.error('加载参数分类数据失败!')
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(',')
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'only') {
        this.onlyParamsType = res.data
        console.log(this.onlyParamsType)
      } else if (this.activeName === 'many') {
        this.manyParamsType = res.data
        console.log(this.manyParamsType)
      }
    },
    handleChange () {
      if (this.value.length === 2) {
        this.value = []
        this.onlyParamsType = []
        this.manyParamsType = []
      } else {
        this.getParamsType()
      }
    },
    tabClick () {
      this.getParamsType()
      if (this.activeName === 'many') {
        this.title = '添加动态参数'
        this.addForm.attr_sel = ['many']
      } else {
        this.title = '添加静态属性'
        this.addForm.attr_sel = ['only']
      }
    },
    // 关闭添加属性弹窗
    addDialogClose () {
      this.$refs.addFormRef.resetFields()
    },
    // 关闭编辑属性弹窗
    editDialogClose () {
      this.$refs.editFormRef.resetFields()
    },
    // 删除
    deleteRoles (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(
          `categories/${this.value[2]}/attributes/${id}`)
        if (res.meta.status === 200) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          // 刷新列表
          await this.getParamsType()
        } else {
          this.$message({
            type: 'error',
            message: '删除失败!'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    saveAttr () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请输入参数名称!')
        const { data: res } = await this.$http.post(
          `categories/${this.value[2]}/attributes`,
          this.addForm)
        if (res.meta.message !== 201) return this.$message.error('添加属性失败！')
        console.log(res)
        this.addDialogVisible = false
        await this.getParamsType()
      })
    },
    // 打开编辑弹窗
    async openUpdate (id) {
      console.log(id)
      if (this.activeName === 'many') {
        this.editTitle = '编辑动态参数'
        this.addForm.attr_sel = ['many']
      } else {
        this.editTitle = '编辑静态属性'
        this.addForm.attr_sel = ['only']
      }
      // 调用接口获取数据
      const { data: res } = await this.$http.get(
        `categories/${this.value[2]}/attributes/${id}`,
        {
          params: {
            attr_sel: this.editForm.attr_sel,
            attr_vals: this.editForm.attr_vals
          }
        })
      if (res.meta.status !== 200) return this.$message.error('获取属性数据失败!')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 编辑属性保存
    UpdateAttr (id) {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写属性!')
        const { data: res } = await this.$http.put(
          `categories/${this.value[2]}/attributes/${this.editForm.attr_id}`,
          this.editForm)
        if (res.meta.status !== 200) return this.$message.error('编辑属性失败!')
        this.$message.success('编辑属性成功!')
        this.editDialogVisible = false
        await this.getParamsType()
      })
    },
    // 删除标签信息
    async deleteTag (row, index) {
      // 删除对应索引
      row.attr_vals.splice(index, 1)
      console.log(row)
      this.editForm.attr_id = row.attr_id
      this.editForm.attr_name = row.attr_name
      if (this.activeName === 'many') {
        this.editForm.attr_sel = ['many']
      } else {
        this.editForm.attr_sel = ['only']
      }
      this.editForm.attr_vals = row.attr_vals.join(',')
      // 调用接口删除标签
      const { data: res } = await this.$http.put(
        `categories/${this.value[2]}/attributes/${this.editForm.attr_id}`,
        this.editForm)
      if (res.meta.status !== 200) return this.$message.error('编辑标签失败!')
      this.$message.success('编辑标签成功!')
      console.log(this.editForm)
    },
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async handleInputConfirm (row) {
      const inputValue = row.inputValue
      if (inputValue) {
        if (this.activeName === 'many') {
          row.attr_vals.push(inputValue)
        } else {
          row.attr_vals.push(inputValue)
        }
        this.editForm.attr_name = row.attr_name
        this.editForm.attr_sel = row.attr_sel
        this.editForm.attr_vals = row.attr_vals
        this.editForm.attr_id = row.attr_id
        if (this.activeName === 'many') {
          this.editForm.attr_sel = ['many']
        } else {
          this.editForm.attr_sel = ['only']
        }
        this.editForm.attr_vals = this.editForm.attr_vals.join(',')
        // 调用接口
        const { data: res } = await this.$http.put(
          `categories/${this.value[2]}/attributes/${this.editForm.attr_id}`,
          this.editForm)
        if (res.meta.status !== 200) return this.$message.error('编辑失败!')
        this.$message.success('编辑成功!')
      }
      row.inputVisible = false
      row.inputValue = ''
    }
  },
  created () {
    this.getAllGoodsType()
  },
  computed: {
    // 如果按钮需要被禁用，则返回true，否则返回false
    isBtnDisabled () {
      if (this.value.length !== 3) {
        return true
      }
      return false
    }
  }
}
</script>

<style lang="less" scoped>
  .cat_opt {
    margin-top: 10px;
  }
  .tabs_top {
    margin-top: 10px;
  }
  .el-tag {
    margin-right: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 150px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
